import fetch from 'isomorphic-fetch'
import qs from 'qs'

import storage from '../libs/utils/storage'

const OA_SERVER = 'https://oaapp.hiido.com/'
const API_OA_LOGIN = 'appService/login'

export const USER_LOGIN_REQUEST = 'USER_LOGIN_REQUEST'
export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'
export const USER_LOGIN_FAILURE = 'USER_LOGIN_FAILURE'

const loginRequest = () => {
  return {
    type: USER_LOGIN_REQUEST
  }
}

const loginSuccess = (employeeCode, token, keepLogin) => {
  return {
    type: USER_LOGIN_SUCCESS,
    employeeCode,
    token,
    keepLogin
  }
}

export const userLogin = (username, password, keepLogin = false) => {
  return (dispatch, getStates) => {

    dispatch(loginRequest())

    const user = storage.load('user')
    if (user) {
      dispatch(loginSuccess(user.employeeCode, user.token, true))
      return null
    }

    return fetch(OA_SERVER + API_OA_LOGIN, {
      // mode: 'no-cors',
      method: 'POST',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: qs.stringify({
        userName: username,
        password: password,
        authCode: '',
        usecode: 1,
        clientInfo: JSON.stringify({
          "deviceId": "14207AB2-F855-49F9-AAE7-CD1F2A50343A",
          "os": "iPhone OS 9.3.1",
          "hardware": "iPhone7,1",
          "version": "1.2.0",
          "type": "IOS"
        })
      })
    })
    .then(response => response.json())
    .then(json => {
      if (json.code == '200') {
        dispatch(loginSuccess(json.employeeCode, json.token, keepLogin))
      }
    }, (err) => {
      console.log(err)
    })

  }
}